package com.jielihaofeng.cosmic.form.plugin;

import com.jielihaofeng.cosmic.event.BeforeClickEvent;
import com.jielihaofeng.cosmic.form.control.Button;
import com.jielihaofeng.cosmic.form.control.Control;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.util.Optional;

/**
 * @author Johnnie Wind
 * @description
 * @date 2021/11/29 10:02
 */
public class AbstractFormPlugin implements IFormPlugin {

    private List<Control> controlList = new ArrayList<>();

    public AbstractFormPlugin() {
    }

    public AbstractFormPlugin(List<Control> controlList) {
        this.controlList = controlList;
    }

    public void initializeControl(Control... controls) {
        for (Control control : controls) {
            controlList.add(control);
        }
    }

    public void initializeControl(List<Control> controls) {
        controlList.addAll(controls);
    }

    public void addClickListeners(String... keys) {
        String[] keyArray = keys;
        int length = keyArray.length;

        for (int i = 0; i < length; ++i) {
            String key = keyArray[i];
            Optional<Control> first = controlList.stream().filter(control -> key.equals(control.getKey())).findFirst();
            if (first.isPresent()) {
                Control control = first.get();
                if (control instanceof Button) {
                    ((Button) control).addClickListener(this);
                }
            }
        }

    }

    @Override
    public void beforeClick(BeforeClickEvent evt) {
        System.out.println("beforeClick");
        // 取消事件
//        evt.setCancel(true);
    }

    @Override
    public void click(EventObject evt) {
        System.out.println("click");
    }
}
